在管理股票清單時,我們常常需要「篩選」、「轉換」、「排序」資料。
C# 提供了 LINQ (Language Integrated Query),可以用直覺的方式來查詢集合資料。
LINQ 主要有兩種寫法:
stocks.Where(x => x.Code == "2330")
from s in stocks where s.Code == "2330" select s
初學時建議用方法語法,比較直觀。
我們先準備一份股票清單(至少 10 筆)。
定義DTO:
using LiteDB;
namespace TwStockMaster.Utils.Models
{
    /// <summary>
    /// Stock profile master record for Taiwan securities and indices.
    /// 台灣證券與指數的主檔資料。
    /// </summary>
    public sealed class StockProfile
    {
        // LiteDB
        [BsonId]
        public string Code { get; set; } = default!;
        /// <summary>
        /// Localized display name.
        /// 中文名稱。
        /// </summary>
        public string Name { get; set; } = default!;
        /// <summary>
        /// Market board code (default TSE).
        /// 市場板別代碼(預設為上市)。
        /// </summary>
        public MarketCode Market { get; set; } = MarketCode.TSE;
        /// <summary>
        /// Country code (default TW).
        /// 國家代碼(預設為台灣)。
        /// </summary>
        public Country Country { get; set; } = Country.TW;
        /// <summary>
        /// Industry/sector mapping if applicable.
        /// 產業別(如屬於某產業或子產業)。
        /// </summary>
        public string? Industry { get; set; }
        /// <summary>
        /// Board/Category tags (optional, e.g., ETF/ETN/ESG).
        /// 類別標籤(選用,例如 ETF/ETN/ESG)。
        /// </summary>
        public string[]? Tags { get; set; }
        /// <summary>
        /// Last time the profile was refreshed (UTC).
        /// 主檔最後更新時間(UTC)。
        /// </summary>
        public DateTime LastUpdatedUtc { get; set; }
    }
}
範例:
using System;
using System.Collections.Generic;
using System.Linq;
using TwStockMaster.Utils.Models;
class Program
{
    static void Main()
    {
        List<StockProfile> stocks = new List<StockProfile>
        {
            new StockProfile { Code = "2330", Name = "台積電", Industry = "半導體", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2303", Name = "聯電", Industry = "半導體", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2317", Name = "鴻海", Industry = "電子代工", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2881", Name = "富邦金", Industry = "金融", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2882", Name = "國泰金", Industry = "金融", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "1216", Name = "統一", Industry = "食品", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "1301", Name = "台塑", Industry = "塑膠", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2002", Name = "中鋼", Industry = "鋼鐵", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2610", Name = "華航", Industry = "航運", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2603", Name = "長榮", Industry = "航運", LastUpdatedUtc = DateTime.UtcNow },
        };
    }
}
假設我們有個需求:找到「金融產業」的股票。
var financeStocks = stocks.Where(s => s.Industry == "金融");
foreach (var stock in financeStocks)
{
    Console.WriteLine($"{stock.Code} {stock.Name}");
}
輸出:
2881 富邦金
2882 國泰金
有時候只想要股票代號與名稱,不需要完整物件。
var simpleList = stocks.Select(s => new { s.Code, s.Name });
foreach (var item in simpleList)
{
    Console.WriteLine($"{item.Code} {item.Name}");
}
輸出:
2330 台積電
2303 聯電
2317 鴻海
...
假設我們想依照 代號排序。
var ordered = stocks.OrderBy(s => s.Code);
foreach (var s in ordered)
{
    Console.WriteLine($"{s.Code} {s.Name}");
}
輸出(部分):
1216 統一
1301 台塑
2002 中鋼
2303 聯電
2330 台積電
...
using System;
using System.Collections.Generic;
using System.Linq;
using TwStockMaster.Utils.Models;
class Program
{
    static void Main()
    {
        List<StockProfile> stocks = new List<StockProfile>
        {
            new StockProfile { Code = "2330", Name = "台積電", Industry = "半導體", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2303", Name = "聯電", Industry = "半導體", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2317", Name = "鴻海", Industry = "電子代工", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2881", Name = "富邦金", Industry = "金融", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "1301", Name = "台塑", Industry = "塑膠", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2002", Name = "中鋼", Industry = "鋼鐵", LastUpdatedUtc = DateTime.UtcNow },
        };
        var query = stocks
            .Where(s => s.Industry == "半導體")           // 篩選產業
            .OrderBy(s => s.Code)                         // 依代號排序
            .Select(s => new { s.Code, s.Name });         // 投影出需要的欄位
        foreach (var item in query)
        {
            Console.WriteLine($"{item.Code} {item.Name}");
        }
    }
}
2303 聯電
2330 台積電
這樣的範例一次示範了 Where → OrderBy → Select 的流程。
今天我們學會了:
Where:篩選資料Select:投影資料OrderBy:排序資料